package com.veo.controller;

import com.veo.service.BlogService;
import com.veo.service.TagService;
import com.veo.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 8, sort = {"updatedTime"}, direction = Sort.Direction.DESC) Pageable pageable, Model model){
//        int i= 10 /0;
//        String blog = null;
//        if (blog == null){
//            throw new NotFoundException("博客不存在");
//        }

        model.addAttribute("page",blogService.listBlog(pageable));
        model.addAttribute("types",typeService.listTypeTop(6 ));
        model.addAttribute("tags",tagService.listTagTop(10));
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));
        return "index";
    }

    //返回博客详情页面
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable("id") Long id,Model model){
        model.addAttribute("blog",blogService.getAndConvertBlog(id));
        return "blog";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 8, sort = {"updatedTime"}, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam String query, Model model){
        model.addAttribute("page",blogService.listBlog( "%" + query + "%", pageable));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/footer/newblog")
    public String newBLogs(Model model){
        model.addAttribute("newBlogs",blogService.listRecommendBlogTop(3));
        return "commons :: newBlogList";
    }

}
